package ido.com.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Parse the project plan from:
 * http://www.iteamwork.com/
 * and use Google CAL API
 * @author greenido
 * 
 */
public class ParsePlan {

    private static final Log LOG = LogFactory.getLog(GetMethod.class);
    private ArrayList<GCalEvent> events;
    private String projectName;
    
 
    private HttpClient client;

    /**
     * 
     */
    public ParsePlan() {
        events = new ArrayList<GCalEvent>();
        client = new HttpClient(); 
        client.getHttpConnectionManager().getParams().setConnectionTimeout(
                30000);
    }

    public String getProjectName() {
        return projectName;
    }

    /**
     * Loads the page at the given URL from a separate thread.
     * @param url
     */
    private String getPage(String projectUrl) throws IOException {
        String body = "";
        GetMethod get = new GetMethod(projectUrl);
        get.setFollowRedirects(true);
        int getResultCode = client.executeMethod(get);
        LOG.debug("the getRes of: " + projectUrl + " is: " + getResultCode);
        body = get.getResponseBodyAsString();
        return body;
    }

    /**
     * ugly parsing - but it's like life... simple and working.
     */              
    public void parsePage(String projectUrl) throws Exception {
        String pageData = getPage(projectUrl);

        int st = pageData.indexOf("tw.modproject?pid=");
        int end = pageData.indexOf(">", st + 15);
        st = pageData.indexOf("<", end + 2);
        projectName = pageData.substring(end+1, st);
        //@@  System.out.print("data: " + pageData);
        st = pageData.indexOf("No.");
        pageData = pageData.substring(st);
        int curSt = pageData.indexOf("<td valign=\"top\" class=\"normal");
        while (curSt > -1) {
            st = pageData.indexOf(">", curSt + 1);
            end = pageData.indexOf("</td>", st + 3);
            String title = pageData.substring(st + 1, end);
            title = title.replaceAll("\\<.*?\\>", "");
            st = pageData.indexOf("valign=\"top\" nowrap class=\"normal\">",
                    end + 10);
            st = pageData.indexOf("valign=\"top\" nowrap class=\"normal\">",
                    st + 15);
            end = pageData.indexOf("</td>", st + 35);
            String date = pageData.substring(st + 35, end).replaceAll("&nbsp;",
                    " ");
            date = date.replaceAll("\\<.*?\\>", "");
            date = date.replaceAll("'", "");

            st = pageData.indexOf(
                    "width=\"48\" valign=\"top\" class=\"normal\">", end + 10);
            end = pageData.indexOf("</td>", st + 35);
            String desc = title + " owner: " + pageData.substring(st + 39, end) + " " + projectName;

            events.add(new GCalEvent(title, desc, date));
            //
            curSt = pageData.indexOf("<td valign=\"top\" class=\"normal", end);
        }

    }

    public ArrayList<GCalEvent> getEvents() {
        return events;
    }

    public void printEvents() {
        int i = 0;
        for (Iterator iterator = events.iterator(); iterator.hasNext();) {
            GCalEvent event = (GCalEvent) iterator.next();
            System.out.println((i++) + ") event: " + event);
        }
    }

    /**
     * unit test
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        System.out.println("-- Start");
        ParsePlan parser = new ParsePlan();
        parser.parsePage("http://www.iteamwork.com/cgi-bin/cgii/tw.tasks?pid=100318");
        parser.printEvents();

        System.out.println("-- End");

    }
}
